﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace ACEPAPI
{
    /// <summary>
    /// ESC/POS 客户端 - 使用System.Net.TcpClient
    /// </summary>
    public class EPClientTcp
    {
        /// <summary>
        /// TCPClient
        /// </summary>
        private TcpClient tcpClient;

        /// <summary>
        /// 当前服务端IP地址
        /// </summary>
        public IPAddress IPAddress { get; set; }

        /// <summary>
        /// 当前服务端IP端口
        /// </summary>
        public int IPPort { get; set; } = 9100;

        private NetworkStream NStream;
        public EPClientTcp(string ipAdd,int ipPort)
        {
            //检测IP地址与端口
            IPAddress _IPAdd;
            if (!IPAddress.TryParse(ipAdd, out _IPAdd))
            {
                throw new ApplicationException("指定的打印机没有正确设置ip地址，无法打印");
            }
            IPAddress = _IPAdd;
            if (ipPort > 0 && ipPort <= 65535)
            {
                IPPort = ipPort;
            }
            else
            {
                throw new ApplicationException("指定的打印机没有正确设置端口地址，无法打印");
            }
        }

        public void Connect()
        {
            if(tcpClient!=null && tcpClient.Connected)
            {
                return;
            }
            tcpClient = new TcpClient(AddressFamily.InterNetwork);
            tcpClient.Connect(IPAddress, IPPort);
            NStream = tcpClient.GetStream();
        }

        public void SendBytes(byte[] sendBytes)
        {
            NStream.Write(sendBytes, 0, sendBytes.Length);
        }

        public byte[] SendReadBytes(byte[] sendBytes)
        {
            byte[] buffer = new byte[64];
            NStream.Write(sendBytes,0,sendBytes.Length);
            NStream.ReadTimeout = 3000;
            int bc = NStream.Read(buffer, 0, buffer.Length);
            byte[] rbytes= new byte[bc];
            Array.Copy(buffer, rbytes, bc);
            return rbytes;
        }
    }
}
